#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/device.h>

#define DEVICE_NAME "led_ctl"
#define CLASS_NAME "led"

static int major_number;
static struct class* led_class = NULL;
static struct device* led_device = NULL;

static ssize_t led_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) {
    char val;
    if (copy_from_user(&val, buf, 1)) return -EFAULT;
    
    // 此处模拟GPIO控制（后续结合QEMU硬件映射）
    printk(KERN_INFO "LED set to: %c\n", val);
    return count;
}

static struct file_operations fops = {
    .owner = THIS_MODULE,
    .write = led_write,
};

static int __init led_init(void) {
    major_number = register_chrdev(0, DEVICE_NAME, &fops);
    if (major_number < 0) {
        printk(KERN_ERR "Failed to register a major number\n");
        return major_number;
    }

    led_class = class_create(CLASS_NAME);  // 修改为单参数
    if (IS_ERR(led_class)) {
        unregister_chrdev(major_number, DEVICE_NAME);
        printk(KERN_ERR "Failed to create device class\n");
        return PTR_ERR(led_class);
    }

    led_device = device_create(led_class, NULL, MKDEV(major_number, 0), NULL, DEVICE_NAME);
    if (IS_ERR(led_device)) {
        class_destroy(led_class);
        unregister_chrdev(major_number, DEVICE_NAME);
        printk(KERN_ERR "Failed to create the device\n");
        return PTR_ERR(led_device);
    }

    printk(KERN_INFO "LED driver loaded successfully\n");
    return 0;
}

static void __exit led_exit(void) {
    device_destroy(led_class, MKDEV(major_number, 0));
    class_destroy(led_class);
    unregister_chrdev(major_number, DEVICE_NAME);
    printk(KERN_INFO "LED driver unloaded\n");
}

module_init(led_init);
module_exit(led_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple LED driver");
MODULE_VERSION("1.0");